/**
 * Created by jiangzhiyong on 15/10/14.
 */
Array.prototype.remove = function(s) {   
    for (var i = 0; i < this.length; i++) {   
        if (s == this[i])   
            this.splice(i, 1);   
    }   
}   
   
function Map() {   
    /** 存放键的数组(遍历用到) */  
    this.keys = new Array();   
    /** 存放数据 */  
    this.data = new Object();   
       
    /**  
     * 放入一个键值对  
     * @param {String} key  
     * @param {Object} value  
     */  
    this.put = function(key, value) {   
        if(this.data[key] == null){   
            this.keys.push(key);   
        }   
        this.data[key] = value;   
    };   
       
    /**  
     * 获取某键对应的值  
     * @param {String} key  
     * @return {Object} value  
     */  
    this.get = function(key) {   
        return this.data[key];   
    };   
       
    /**  
     * 删除一个键值对  
     * @param {String} key  
     */  
    this.remove = function(key) {   
        this.keys.remove(key);   
        this.data[key] = null;   
    };   
       
    /**  
     * 遍历Map,执行处理函数  
     *   
     * @param {Function} 回调函数 function(key,value,index){..}  
     */  
    this.each = function(fn){   
        if(typeof fn != 'function'){   
            return;   
        }   
        var len = this.keys.length;   
        for(var i=0;i<len;i++){   
            var k = this.keys[i];   
            fn(k,this.data[k],i);   
        }   
    };   
       
    /**  
     * 获取键值数组(类似Java的entrySet())  
     * @return 键值对象{key,value}的数组  
     */  
    this.entrys = function() {   
        var len = this.keys.length;   
        var entrys = new Array(len);   
        for (var i = 0; i < len; i++) {   
            entrys[i] = {   
                key : this.keys[i],   
                value : this.data[i]   
            };   
        }   
        return entrys;   
    };   
       
    /**  
     * 判断Map是否为空  
     */  
    this.isEmpty = function() {   
        return this.keys.length == 0;   
    };   
       
    /**  
     * 获取键值对数量  
     */  
    this.size = function(){   
        return this.keys.length;   
    };   
       
    /**  
     * 重写toString   
     */  
    this.toString = function(){   
        var s = "{";   
        for(var i=0;i<this.keys.length;i++,s+=','){   
            var k = this.keys[i];   
            s += k+"="+this.data[k];   
        }   
        s+="}";   
        return s;   
    };   
}   
  
var Common = {
    init: function() {
        Common.init_login();
        Common.init_pagination(0);
		$(".btn-default").click(function(){
        	$(".diolag").modal("hide");
        });
    },
    init_login : function() {
    		//读取token，如果没有就跳转到登录页面
    		var token = $.cookie("token");
    		if (token == null || token == "") {
    			window.location.href = "login.html";
    		}
    },
    init_pagination : function(pageIndex) {
//  		$(".pagination li a").click(function() {
//  			alert($(this).text());
//  		});
		var selectIndex = 0;
		if (pageIndex > 0) {
			selectIndex = pageIndex;
		}
		if (pageIndex == undefined || pageIndex < 2) {
			pageIndex = 2;
		}
		var pages = $(".pagination li a");
		if (pages != null) {
			for (var i = 1; i< pages.length; i++) {
				$(pages[i]).attr("page", pageIndex - 3 + i);
				$(pages[i]).text(pageIndex - 2 + i);
			}
			$(".pagination li a[page="+selectIndex+"]").parent().addClass("active").siblings("li").removeClass("active");
		}
    },
    //自动登录，拿到sessionID
    auto_login : function() {
		//读取token，如果有就自动登录，如果没有就跳转到登录页面
		var token = $.cookie("token");
		var uri = "/auto-login";
		var data = {
			"token": token
		};
		var host = "http://t1.7kez.com";
		$.ajax({
		    url: host + uri,
		    type: 'post',
		    async: false,
		    data: data,
		    dataType: 'json',
		    success: function (result) {
		        console.log(result);
		        if (result.code == 0) {
		        		var session_id = result.data.sid;
		        		var name = result.data.user.name;
		        		//写入session
		        		$.cookie('session_id', session_id, { expires: Number.MAX_VALUE, path: '/' });
	            		$.cookie('name', name, { expires: Number.MAX_VALUE, path: '/' });
		        		return true;
		        } 
		        return false;
		    }
		});
	}
};

/**
 * 通用的ajax请求接口，session失效就自动登录
 * @param {Object} uri
 * @param {Object} data
 */
function ajax(uri, data, callback) {
    var host = "http://t2.7kez.com";
    var session_id = $.cookie("session_id");
    data['sid'] = session_id;
    $.ajax({
        url: host + uri,
        type: 'post',
        async: true,
        data: data,
        dataType: 'json',
        success: function (result) {
        	
          	console.log(result);
            if (result.code == 0 || result.code == 1) {
            		if (callback) {
            			callback(result);
            		}
            } else if (result.code == 2) {
            		if(Common.auto_login()) {
            			ajax(uri, data);
            		} else{
            			window.parent.location.href = "login.html";
            		}
            } else if (result.code == 4) {
            		alert("数据不存在!");
            } else {
            		alert("请求出错!");
            }
        }
    });
}

function getToken() {
	var host = "http://t2.7kez.com";
	var uri = "/image/uptoken";
	var uptoken = "";
	$.ajax({
        url: host + uri,
        type: 'post',
        async: false,
        data: {},
        dataType: 'json',
        success: function (result) {
        		console.log("getToken() result.uptoken = " + result.uptoken);
            uptoken =  result.uptoken;
        }
    });
    return uptoken;
}

function formatDate (strTime) {
    var date = new Date(strTime*1000);
    return date.getFullYear() + '/'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '/' + ('0' + (date.getDate())).slice(-2)
     + ' ' + ('0' + (date.getHours())).slice(-2)
      + ':' + ('0' + (date.getMinutes())).slice(-2)
       + ':' + ('0' + (date.getSeconds())).slice(-2);

}


$(function(){
    Common.init();
})
